<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
          size="small"
          class="filter-item"
          type="primary"
          @click="addLog"
      >生成台账
      </el-button
      >
      台账账期:
      <el-date-picker
          class="filter-item"
          size="small"
          v-model="listQuery.settlement_date"
          value-format="yyyy-MM"
          type="month"
          placeholder="选择台账账期">
      </el-date-picker>
      创建时间:
      <el-date-picker
          size="small"
          class="filter-item"
          v-model="dateArr"
          type="daterange"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          value-format="yyyy-MM-dd"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
      ></el-date-picker>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" size="small">搜索
      </el-button>
    </div>
    <el-table
        v-loading="listLoading"
        :data="list"
        :row-class-name="tableRowClassName"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
    >
      <el-table-column align="center" label="序号">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="台账账期">
        <template slot-scope="scope">
          {{ moment( scope.row.settlement_date).format('YYYY-MM') }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="总金额">
        <template slot-scope="scope">
          {{ scope.row.total_cost }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单数">
        <template slot-scope="scope">
          {{ scope.row.order_num }}
        </template>
      </el-table-column>
      <el-table-column label="操作人员" min-width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.admin?scope.row.admin.username:"-" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--          label="操作"-->
      <!--          align="center"-->
      <!--          class-name="small-padding fixed-width"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          <download-excel-->
      <!--              v-if="scope.row.status != 'none'"-->
      <!--              class="filter-item"-->
      <!--              :fields="json_fields2"-->
      <!--              :fetch="handleExport2"-->
      <!--              type="xls"-->
      <!--              name="数据统计.xls"-->
      <!--              worksheet="数据统计"-->
      <!--          >-->
      <!--            <el-button-->
      <!--                size="mini"-->
      <!--                type="success"-->
      <!--                :loading="exportLoading"-->
      <!--                @click="userLogsid = scope.row.id"-->
      <!--            >-->
      <!--              导出发放Excel-->
      <!--            </el-button>-->
      <!--          </download-excel>-->
      <!--          <div style="margin-top: 5px">-->
      <!--            <el-button-->
      <!--                v-if="scope.row.status != 'revoked'"-->
      <!--                size="mini" type="warning" @click="revoke(scope.row)">-->
      <!--              撤销发放-->
      <!--            </el-button>-->
      <!--          </div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>

    <div class="pagination-container">
      <el-pagination
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="listQuery.limit"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
        title="生成台账"
        :visible.sync="showaddLog"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        append-to-body
        width="512px"
    >
      <el-form
          ref="addLogform"
          :model="addLogform"
          :rules="addLogRules"
          label-width="120px"
      >
        <el-form-item label="台账账期" prop="img">
          <el-date-picker
              size="small"
              v-model="addLogform.settlement_date"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择台账账期">
          </el-date-picker>
          <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getCount" size="small"
                     style="margin-left: 5px"
                     :loading="getCountBtnLoading"
          >检索
          </el-button>
        </el-form-item>
        <el-form-item label="总成本金额" prop="img">
          {{ data.total_rate }}
        </el-form-item>
        <el-form-item label="总销售结算金额" prop="img">
          {{ data.channel_money }}
        </el-form-item>

        <el-row type="flex" justify="end">
          <el-button @click="showaddLog = false">取消</el-button>
          <el-button type="primary" @click="postaddLog">确认</el-button>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import downloadExcel from 'vue-json-excel'
import {excel2Json} from '@/utils/excel'
import moment from "moment";

export default {
  components: {downloadExcel},
  data() {
    return {
      showaddLog: false,
      addLogRules: {
        reason: [
          {required: true, message: '请填写驳回理由', trigger: 'blur'},
        ],
      },
      addLogform: {
        users: [],
        date: '',
        start_date: '',
        end_date: '',
      },
      data: {total_rate:0,channel_money:0},
      list: null,
      total: null,
      listLoading: false,
      exportLoading: false,
      listQuery: {
        page: 1,
        limit: 10,
        start_at: '',
        end_at: '',
      },
      userLogsid: '',
      viplist: [],
      json_fields: {
        订单号: {
          field: 'order_id',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        // 自我游订单状态: {
        //   field: 'state',
        //   //自定义回调函数
        //   callback: (value) => {
        //     var state_remark;
        //     switch (value) {
        //       case '0':
        //         state_remark = '新订单'
        //         break;
        //       case '1':
        //         state_remark = '已确认'
        //         break;
        //       case '2':
        //         state_remark = '已成功'
        //         break;
        //       case '3':
        //         state_remark = '已取消'
        //         break;
        //       case '4':
        //         state_remark = '已完成'
        //         break;
        //       default:
        //         state_remark = ''
        //         break;
        //     }
        //
        //     return '<p style="mso-number-format:\'\\@\';">' + state_remark + '</p>'
        //   },
        // },
        下单时间: {
          field: 'order_date',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        渠道结算价: {
          field: 'channel_money',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        联系人姓名: {
          field: 'link_man',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        联系人手机: {
          field: 'link_phone',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        入住时间: {
          field: 'travel_date',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        离店时间: {
          field: 'end_travel_date',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        酒店名称: {
          field: 'hotel',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + (value ? value.inn_name : "") + '</p>'
          },
        },
        售卖房型名称: {
          field: 'room_type',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + (value ? value.room_type_name : "") + '</p>'
          },
        },
        房间间数: {
          field: 'room_num',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        锦江订单编号: {
          field: 'room_num',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        锦江到店时间: {
          field: 'last_arr_time',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        锦江订单状态: {
          field: 'order_state',
          //自定义回调函数
          callback: (value) => {
            var state_remark;
            switch (value) {
              case 1:
                state_remark = '预订成功'
                break;
              case 2:
                state_remark = '已取消'
                break;
              case 3:
                state_remark = '预订未到'
                break;
              case 4:
                state_remark = '已入住'
                break;
              case 5:
                state_remark = '已完成'
                break;
              default:
                state_remark = ''
                break;
            }

            return '<p style="mso-number-format:\'\\@\';">' + state_remark + '</p>'
          },
        },
        锦江支付状态: {
          field: 'pay_state',
          //自定义回调函数
          callback: (value) => {
            var state_remark;
            switch (value) {
              case 0:
                state_remark = '未付款'
                break;
              case 1:
                state_remark = '已付款'
                break;
              case 2:
                state_remark = '退款处理中'
                break;
              case 3:
                state_remark = '已退款'
                break;
              default:
                state_remark = ''
                break;
            }

            return '<p style="mso-number-format:\'\\@\';">' + state_remark + '</p>'
          },
        },
        系统订单号: {
          field: 'system_order_no',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        系统订单状态: {
          field: 'system_order_status',
          //自定义回调函数
          callback: (value) => {
            var state_remark;
            switch (value) {
              case 100:
                state_remark = '下单待处理'
                break;
              case 101:
                state_remark = '下单成功'
                break;
              case 102:
                state_remark = '下单失败'
                break;
              case 201:
                state_remark = '取消订单成功'
                break;
              case 202:
                state_remark = '取消订单失败'
                break;
              default:
                state_remark = ''
                break;
            }

            return '<p style="mso-number-format:\'\\@\';">' + state_remark + '</p>'
          },
        },
        操作处理失败信息: {
          field: 'handle_error_message',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        创建时间: {
          field: 'created_at',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
      },
      json_fields2: {
        用户名: {
          field: 'username',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        用户id: {
          field: 'user_id',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        奖励金额: {
          field: 'reward_value',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
        备注: {
          field: 'remark',
          //自定义回调函数
          callback: (value) => {
            return '<p style="mso-number-format:\'\\@\';">' + value + '</p>'
          },
        },
      },
      dateArr: null,
      getCountBtnLoading: false
    }
  },
  created() {
    this.getList()
  },
  watch: {
    showaddLog() {
      this.addLogform = {
        jin_jiang_orders: [],
        date: '',
        end_travel_date_start_at: '',
        end_travel_date_end_at: '',
      }
    },
    dateArr(newVal, oldVal) {
      if (newVal) {
        this.listQuery.start_at = newVal[0];
        this.listQuery.end_at = newVal[1];
      } else {
        this.listQuery.start_at = "";
        this.listQuery.end_at = "";
      }
    },
  },
  computed: {
    moment() {
      return moment
    },
    //状态：none：未处理 ； pending：处理中 ；completed：已完成； revoke_pending ：撤销处理中；revoked：已撤销
    status() {
      return (val) => {
        switch (val) {
          case 'none':
            return '未处理'
          case 'pending':
            return '处理中'
          case 'completed':
            return '已完成'
          case 'revoke_pending':
            return '撤销处理中'
          case 'revoked':
            return '已撤销'
        }
      }
    },
    revenue_type() {
      return (val) => {
        switch (val) {
          case 'retail_bonus':
            return '零售奖励'
          case 'referral_bonus':
            return '推荐奖励'
          case 'distribution_bonus':
            return '分销奖励'
          case 'expansion_bonus':
            return '级差奖励'
          case 'welfare_bonus':
            return '福利奖励'
          case 'founder_bonus':
            return '创始人分红'
          case 'vip_bonus':
            return 'VIP 分红'
          case 'super_vip_bonus':
            return '钻石分红'
        }
      }
    },
  },
  methods: {

    tableRowClassName({row}) {
      const systemCost = Number(row.system_cost);
      const jinJiangCost = Number(row.jin_jiang_cost);

      if (systemCost === 0) {
        console.log(systemCost);
        return 'row-red';
      }

      if (jinJiangCost === 0) {
        return 'row-blue';
      }

      if (systemCost > 0 && jinJiangCost > 0 && systemCost !== jinJiangCost) {
        return 'row-yellow';
      }

      return '';
    },

    addLog() {
      this.showaddLog = true
    },
    downloadExcel() {
      let a = document.createElement('a')
      a.href = '/订单对账模板.xlsx'
      a.download = '订单对账模板.xlsx'
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    postaddLog() {
      if (!this.addLogform.settlement_date ) {
        this.$message.warning('请选择台账账期')
        return
      }
      return request({
        url: '/api/backend/ledger/create-log',
        method: 'POST',
        data: this.addLogform,
      })
          .then((res) => {
            if (res.code == 0) {
              this.$message({
                type: 'success',
                message: '操作成功',
              })
              this.showaddLog = false
              this.getList()
            }
          })
          .finally((val) => {
            console.log(val)
          })
    },
    handleImportUsers(file) {
      this.addLogform.users = []
      file = file.raw
      if (
          !(file.name.split('.')[1] == 'xlsx' || file.name.split('.')[1] == 'xls')
      ) {
        this.$message.error('上传文件格式不正确，请检查选择的文件')
        return
      }
      excel2Json(file, 1).then((excelData) => {
        console.log(excelData)
        // 处理业务
        if (excelData.length <= 0) {
          this.$message.error('数据不能为空')
          return
        }
        excelData.forEach((element, index) => {
          if (element['锦江订单号']) {
            this.addLogform.jin_jiang_orders.push({
              order_code: element['锦江订单号'],
              total_rate: element['锦江支付总价'],
            })
          }
          console.log(element, '--------', index)
        })
        this.importDataDialogVisible = true
        console.log(this.addLogform.jin_jiang_orders, '=============')
      })
    },
    changedata(val) {
      console.log(val)
      if (val) {
        this.listQuery.start_at = val[0]
        this.listQuery.end_at = val[1]
      } else {
        this.listQuery.start_at = ''
        this.listQuery.end_at = ''
      }
    },
    changeaddLogformdata(val) {
      console.log(val)
      if (val) {
        this.addLogform.end_travel_date_start_at = val[0]
        this.addLogform.end_travel_date_end_at = val[1]
      } else {
        this.addLogform.end_travel_date_start_at = ''
        this.addLogform.end_travel_date_end_at = ''
      }
    },
    handleExport2() {
      this.exportLoading = true
      return request({
        url: '/api/backend/globalReward/userLogs',
        method: 'get',
        params: {
          id: this.userLogsid,
        },
      })
          .then((response) => {
            console.log(response)
            return response.data.data
          })
          .finally((val) => {
            console.log(val)
            this.exportLoading = false
          })
    },
    getList() {
      this.listLoading = true
      request({
        url: '/api/backend/ledger/list',
        method: 'get',
        params: this.listQuery,
      }).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    getCount() {
      if(this.addLogform.settlement_date==null){
        return
      }
      this.getCountBtnLoading = false
      request({
        url: '/api/backend/ledger/getCount',
        method: 'get',
        params: {
          settlement_date: this.addLogform.settlement_date,
        },
      }).then((response) => {
        this.data = response.data

      }).finally(() => function () {
        this.getCountBtnLoading = false
      });
    },
    revoke(row) {
      this.$confirm('是否确认撤销？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            request({
              url: '/api/backend/globalReward/revoke',
              method: 'post',
              data: {
                id: row.id,
              },
            }).then((res) => {
              console.log(res)
              if (res.code == 0) {
                this.$message({
                  type: 'success',
                  message: '操作成功',
                })
                this.getList()
              }
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            })
          })
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 6px;
}

::v-deep .row-red {
  background-color: #ffecec !important;
}

::v-deep .row-blue {
  background-color: #e0f0ff !important;
}

::v-deep .row-yellow {
  background-color: #fffbe0 !important;
}

</style>
